#!/usr/bin/env python
# -*- coding:utf-8 -*-
#下载喜马拉雅音频文件
#参考：http://www.jianshu.com/p/fc2e83c6583c

import urllib
import urllib2
import json

DEBUG = True
HTTP_PROXY='132.122.1.4:9898'



def get_response_by_url(url):
    txt = None
    if DEBUG:
        user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.9.5.1000 Chrome/39.0.2146.0 Safari/537.36'
        proxy = urllib2.ProxyHandler({'http':HTTP_PROXY})
        opener = urllib2.build_opener(proxy)
        opener.addheaders = [('User-agent', user_agent)]
        urllib2.install_opener(opener)
    try:
        txt = urllib2.urlopen(url,timeout=60).read()
    except Exception,e:
        print e
    return txt




''''
 if txt !="" and len(txt) > 100:
        js = json.loads(txt)
        print json.dumps(js,indent=4)
        download_url=None
        if js.has_key('play_path_32'):
            download_url = js.get('play_path_32')
        elif js.has_key('play_path_64'):
            download_url = js.get('play_path_64')
        return download_url

'''

def schedule(a,b,c):
    per = 100.0 * a * b / c
    if per > 100:
        per =100
    print '%.2f%%' % per

def download_m4a_file(m4a_url):
    if m4a_url !="":
        file_name='E:\\vscodespace\\ximalaya\\download\\1.mp3'
        urllib.urlretrieve(m4a_url,file_name,schedule)
        




if  __name__ == '__main__':
    url = 'http://www.ximalaya.com/tracks/8671196.json'
    m4a_url='http://audio.xmcdn.com/group7/M00/6D/A8/wKgDWlXvKLPy4FpKACm5KaeExMA779.m4a'
    #print get_response_by_url(url)
    download_m4a_file(m4a_url)




















